/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { MailTwoTone, MobileTwoTone } from '@ant-design/icons';
import { Alert, message } from 'antd';
import React, { useState } from 'react';
import ProForm, { ProFormCaptcha, ProFormText } from '@ant-design/pro-form';
import type { Dispatch } from 'umi';
import { connect, useIntl, FormattedMessage } from 'umi';
import type { StateType } from '@/models/login';
import type { LoginParamsType } from '@/services/login';
import { getFakeCaptcha } from '@/services/login';
import type { ConnectState } from '@/models/connect';
import { patterns, patternCheck } from '@/utils/patterns';
import styles from './index.less';

interface LoginProps {
  dispatch: Dispatch;
  userLogin: StateType;
  submitting?: boolean;
}

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type='error'
    showIcon
  />
);

const Login: React.FC<LoginProps> = (props) => {
  const { userLogin = {}, submitting } = props;
  const { status, type: loginType } = userLogin;
  const [type] = useState<string>('mobile');
  const [refreshKey, updateRefreshKey] = useState<number>(0);
  const intl = useIntl();

  const handleSubmit = (values: LoginParamsType) => {
    const { dispatch } = props;
    dispatch({
      type: 'login/login',
      payload: { ...values },
    });
  };

  return (
    <div className={styles.main}>
      <ProForm
        initialValues={{
          autoLogin: true,
        }}
        submitter={{
          render: (_, dom) => dom.pop(),
          submitButtonProps: {
            loading: submitting,
            size: 'large',
            style: {
              width: '100%',
            },
          },
        }}
        onFinish={async (values) => {
          handleSubmit(values);
        }}
      >
        {status === 'error' && loginType === 'mobile' && !submitting && (
          <LoginMessage content='验证码错误' />
        )}
        {type === 'mobile' && (
          <>
            <ProFormText
              fieldProps={{
                size: 'large',
                prefix: <MobileTwoTone className={styles.prefixIcon} />,
              }}
              name='mobile'
              placeholder={intl.formatMessage({
                id: 'pages.login.phoneNumber.placeholder',
                defaultMessage: '手机号',
              })}
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage
                      id='pages.login.phoneNumber.required'
                      defaultMessage='请输入手机号！'
                    />
                  ),
                },
                patterns.mobile,
              ]}
            />
            <ProFormCaptcha
              key={refreshKey}
              fieldProps={{
                size: 'large',
                prefix: <MailTwoTone className={styles.prefixIcon} />,
              }}
              captchaProps={{
                size: 'large',
              }}
              placeholder={intl.formatMessage({
                id: 'pages.login.captcha.placeholder',
                defaultMessage: '请输入验证码',
              })}
              captchaTextRender={(timing, count) =>
                timing
                  ? `${count} ${intl.formatMessage({
                      id: 'pages.getCaptchaSecondText',
                      defaultMessage: '获取验证码',
                    })}`
                  : intl.formatMessage({
                      id: 'pages.login.phoneLogin.getVerificationCode',
                      defaultMessage: '获取验证码',
                    })
              }
              name='code'
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage
                      id='pages.login.captcha.required'
                      defaultMessage='请输入验证码！'
                    />
                  ),
                },
              ]}
              onGetCaptcha={async (mobile) => {
                const { code, message: msg } = patternCheck({ mobile });
                const isRightMobile = code === 0;
                const response = isRightMobile
                  ? await getFakeCaptcha({ mobile, userType })
                  : {
                      code,
                      msg,
                    };
                if (response.code == 0) {
                  message.success('验证码已发送！');
                } else {
                  message.error(response.msg);
                  if (!isRightMobile) {
                    // 手机号错误：
                    // 刷新获取验证码组件，粗暴解决 ProFormCaptcha 组件bug
                    updateRefreshKey(new Date().getTime());
                  }
                }
              }}
            />
          </>
        )}
      </ProForm>
    </div>
  );
};

export default connect(({ login, loading }: ConnectState) => ({
  userLogin: login,
  submitting: loading.effects['login/login'],
}))(Login);
